// const resourceList = []

let isDownloading = false;
const resourceList = {

}
const list = document.querySelector('.list_common')
const btnDownload = document.querySelector('.btn_download')
let isLoading = false;  // 是否正在下载文件

const domainList = ['gemioli.com']
const pattern = {
    'gemioli.com':{
        getStart: (url)=>{return url.indexOf('.com/')+5}
    }
}
const getHostFromUrl = url =>{
    const result = url.match(/\/\/([^/]+)\//)
    if(result){
        return result[1]
    }else{
        return result
    }
}

const getPath = resource =>{
    let path = null
    const content = resource.content
        ,url = resource.url
        ,host = getHostFromUrl(url)
        ,type = content.mimeType.substring(content.mimeType.indexOf('/')+1)
        ;

    if(domainList.includes(host)){
        const start = pattern[host].getStart(url)
            ,end = url.lastIndexOf('?')==-1?url.length:url.lastIndexOf('?')
            ;
        console.log('起点',start,end)
        path =  url.substring(start,end)
        if(path.indexOf('.')==-1){ // path没有文件名称
            if(type==='javascript'){
                path += 'index.js';
            }else if(type==='html'){
                path += 'index.html'
            }

        }
    }
    return path

}

/**
 * 
 * @param {*} callback 
 */
function getXHRs(callback) {
    var xhrResources = [];
    if (document.getElementById('check-xhr').checked) {
        chrome.devtools.network.getHAR(function (logInfo) {
            logInfo.entries.map(function (entry) {
                if (reqs[entry.request.url]) {
                    console.log('Found in Resource Collector: ', entry.request.url);
                    xhrResources.push(Object.assign({}, entry.request, {
                        getContent: function (cb) {
                            cb(reqs[entry.request.url].body, reqs[entry.request.url].encoding);
                            return true;
                        },
                        type: entry.response.content.mimeType || 'text/plain',
                        isStream: false
                    }));
                } else {
                    xhrResources.push(Object.assign({}, entry.request, {
                        getContent: entry.getContent,
                        type: entry.response.content.mimeType || 'text/plain',
                        isStream: (entry.response.content.mimeType || '').indexOf('event-stream') !== -1
                    }));
                }
            });
            callback(xhrResources);
        });
    } else {
        callback(xhrResources);
    }
}


/**
 * 根据url和文件类型生成文件存储路径
 * @param {Object} resource 
 * @returns {String}
 */
const getFilePath = (resource)=>{
    const content = resource.content
        ,url = resource.url
        ,start = url.indexOf('play2/')+6
        ,end = url.lastIndexOf('?')==-1?url.length:url.lastIndexOf('?')
        ,type = content.mimeType.substring(content.mimeType.indexOf('/')+1)
        ,host = getHostFromUrl(url)
        ;
    if(domainList.includes(host)){
      let path = getPath(resource)
      return path
    }else if(url.indexOf('lagged.com')!=-1&&url.indexOf('play2/')!=-1){   // 判断url属于lagged
        let path =  url.substring(start,end)
        if(path.indexOf('.')==-1){ // path没有文件名称
            if(type==='javascript'){
                path += 'index.js';
            }else if(type==='html'){
                path += 'index.html'
            }
    
        }
        console.log('文件存储路径',path,';类型：',type)
        return path;
    }else{
        return '';
    }
}

/**
 * 下载资源文件
 * @param {Object} resource
 */
const downloadResource = (resource)=>{
    const url = resource.url
        ,path = getFilePath(resource)
        ;
    if(path){
        chrome.downloads.download({
            url: url,
            filename: path,
            saveAs: false,
            conflictAction: 'overwrite',    // 覆盖重名文件
        }, (id)=>{
           console.log(`始下载文件: ${url};下载编号: ${id}`)
        })
    }

}

chrome.devtools.inspectedWindow.getResources(function (resources) {
    if (!isDownloading) {
        console.log('Static resources count: ' + resources.length);
    }
});

//This can be used for identifying when ever a new resource is added
chrome.devtools.inspectedWindow.onResourceAdded.addListener(function (resource) {
    if (resource.url.indexOf('http') === 0) {
        console.log('添加了新的文件')
        // document.getElementById('debug').innerHTML += resource.url + '\n';
    }
});


chrome.devtools.network.onRequestFinished.addListener(
function(data) {
    console.log(data,'获取到请求数据')

    const request = data.request
    const type = data._resourceType
    const url = request.url
    const content = data.response.content
    const li = document.createElement('li')
    li.innerHTML = `${type}--${content.mimeType}: ${request.url}`
    list.append(li)

    const encode_url = encodeURI(url)
    if(!resourceList[encode_url]){
        resourceList[encode_url]=({
            url: request.url,
            type: type,
            content: content
        })

    }    
});

btnDownload.addEventListener('click',e=>{
    isLoading = true;
    console.log(resourceList,'待下载的资源列表')
    chrome.downloads.setShelfEnabled(false);
    for(const i in resourceList ){
        const resource = resourceList[i]
        console.log('即将下载',resource.url)
        // Disable download notification
        downloadResource(resource)
    }
})

chrome.downloads.onChanged.addListener(obj=>{
    console.log('downloads onChanged',obj)
    if(obj.endTime){
        console.log(obj.id,'下载结束')
    }
})
